const fs = require("fs");
const http = require("http");

http
  .createServer((request, response) => {
    // console.log("a request", getPrototypeChain(request), getPrototypeChain(response));
    // response.end("Hi YK菌"); // 这个end不太好，不好理解
    // TODO? response和request 都是流

    const { url, method, headers } = request;
    console.log("url:", url);
    if (url === "/" && method === "GET") {
      fs.readFile("index.html", (err, data) => {
        if (err) {
          response.writeHead(500, {
            "Content-Type": "text/plain;charset=utf-8",
          });
          response.end("500 服务器挂了，兄弟！！！");
        }
        response.statusCode = 200;
        response.setHeader("Content-Typr", "text/html");
        response.end(data);
      });
    } else if (url === "/users1" && method === "GET") {
      response.writeHead(200, { "Content-Type": "application/json" });
      response.end(JSON.stringify({ name: "yk菌" }));
    } else if (method === "GET" && headers.accept.indexOf("image/*" !== -1)) {
      // 拿到所有图片
      // 不要直接使用readFile读取， 因为它要把全部图片内容加载到服务器
      // 使用 流 stream ！！！！
      fs.createReadStream("." + url).pipe(response);
    } else {
      response.statusCode = 400;
      response.setHeader("Content-Type", "text/plain;charset=utf-8");
      response.end("404 找不到了呀！");
    }
  })
  .listen(3000, () => {
    console.log("Server at 3000");
  });

function getPrototypeChain(obj) {
  const protoChain = [];
  while ((obj = Object.getPrototypeOf(obj))) {
    protoChain.push(obj);
  }
  return protoChain;
}
